// 定义传感器引脚
#define LEFT_SENSOR_PIN 16
#define CENTER_SENSOR_PIN 18
#define RIGHT_SENSOR_PIN 17

// 定义电机引脚
#define LEFT_MOTOR_PIN1 5
#define LEFT_MOTOR_PIN2 6
#define RIGHT_MOTOR_PIN1 9
#define RIGHT_MOTOR_PIN2 10

// 定义阈值
#define THRESHOLD 400
#define THRESHOLD_BLACK 100

// 定义枚举类型表示转向
enum TurnDirection {
  LEFT,
  RIGHT
};

// 函数声明
void turn(TurnDirection direction);

void setup() {
  // 初始化传感器和电机引脚
  pinMode(LEFT_SENSOR_PIN, INPUT);
  pinMode(CENTER_SENSOR_PIN, INPUT);
  pinMode(RIGHT_SENSOR_PIN, INPUT);
  pinMode(LEFT_MOTOR_PIN1, OUTPUT);
  pinMode(LEFT_MOTOR_PIN2, OUTPUT);
  pinMode(RIGHT_MOTOR_PIN1, OUTPUT);
  pinMode(RIGHT_MOTOR_PIN2, OUTPUT);

  // 初始化串行通信
  Serial.begin(9600);
}

void loop() {
//  start(5,6,150);
//  start(9,10,150);
  // 寻迹
  trackLine();
}

// 寻迹
void trackLine() {
  // 读取传感器数值
  int leftSensor = analogRead(LEFT_SENSOR_PIN);
  int centerSensor = analogRead(CENTER_SENSOR_PIN);
  int rightSensor = analogRead(RIGHT_SENSOR_PIN);

  // 根据传感器数值调整转向
  if (centerSensor < THRESHOLD_BLACK) {
    // 直行
    spin(150, 150); // 调用 spin() 函数控制直行
  } else if (leftSensor > THRESHOLD_BLACK && rightSensor < THRESHOLD_BLACK) {
    // 左转弯
    turn(LEFT); // 调用 turn() 函数控制左转
  } else if (leftSensor < THRESHOLD_BLACK && rightSensor > THRESHOLD_BLACK) {
    // 右转弯
    turn(RIGHT); // 调用 turn() 函数控制右转
  } else {
    // 其他情况
    stop(); // 停止车辆
  }
}

// 控制转弯
void turn(TurnDirection direction) {
  // 根据转弯方向控制电机转向
  if (direction == LEFT) {
    // 左转弯
    spin(-150, 150); // 调用 spin() 函数控制左转
  } else {
    // 右转弯
    spin(150, -150); // 调用 spin() 函数控制右转
  }
}

// 停止函数
void stop() {
  digitalWrite(LEFT_MOTOR_PIN1, LOW);
  digitalWrite(LEFT_MOTOR_PIN2, LOW);
  digitalWrite(RIGHT_MOTOR_PIN1, LOW);
  digitalWrite(RIGHT_MOTOR_PIN2, LOW);
}

// 控制电机转动
void spin(int leftSpeed, int rightSpeed) {
  // 控制左电机转动
  if (leftSpeed > 0) {
    analogWrite(LEFT_MOTOR_PIN1, leftSpeed);
    analogWrite(LEFT_MOTOR_PIN2, LOW);
  } else {
    analogWrite(LEFT_MOTOR_PIN1, LOW);
    analogWrite(LEFT_MOTOR_PIN2, -leftSpeed);
  }

  // 控制右电机转动
  if (rightSpeed > 0) {
    analogWrite(RIGHT_MOTOR_PIN1, rightSpeed);
    analogWrite(RIGHT_MOTOR_PIN2, LOW);
  } else {
    analogWrite(RIGHT_MOTOR_PIN1, LOW);
    analogWrite(RIGHT_MOTOR_PIN2, -rightSpeed);
  }
}

void start(int x,int y,int speed)
{
  analogWrite( x , speed );
  analogWrite( y , LOW );
}
